"""
create app
"""


from fastapi import FastAPI
from tortoise.contrib.fastapi import register_tortoise
from fastapi.middleware.cors import CORSMiddleware
from .v1 import v1
from core import settings,get_logger,config



app = FastAPI(description=settings.DESC)

app.include_router(v1,prefix="/api")

# 跨域处理
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# fmt = logging.Formatter(
#     fmt="%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s",
#     datefmt="%Y-%m-%d %H:%M:%S",
# )
# sh = logging.StreamHandler(sys.stdout)
# sh.setLevel(logging.DEBUG)
# sh.setFormatter(fmt)

# handler = logging.handlers.TimedRotatingFileHandler(filename="ims.log", encoding='UTF-8',when="w6")
# handler.setLevel(logging.DEBUG)
#     # 生成并设置文件日志格式
# handler.setFormatter(fmt)

# # will print debug sql
# logger_db_client = logging.getLogger("tortoise.db_client")
# logger_db_client.setLevel(logging.DEBUG)
# logger_db_client.addHandler(sh)
# logger_db_client.addHandler(handler)

# logger_evicorn = logging.getLogger("uvicorn")
# logger_evicorn.setLevel(logging.DEBUG)
# logger_evicorn.addHandler(sh)
# logger_evicorn.addHandler(handler)

# logger_evicorn_error = logging.getLogger("uvicorn.error")
# logger_evicorn_error.setLevel(logging.DEBUG)
# logger_evicorn_error.addHandler(sh)
# logger_evicorn_error.addHandler(handler)

# logger_evicorn_access = logging.getLogger("uvicorn.access")
# logger_evicorn_access.setLevel(logging.DEBUG)
# logger_evicorn_access.addHandler(sh)
# logger_evicorn_access.addHandler(handler)

# 项目启动时 初始化配置
@app.on_event("startup")
def init():
    # 初始化各模块日志配置
    config.init_logger()
    # 不添加logger: uvicorn,否则日志会重复
    for logger in ["fastapi","uvicorn.error","uvicorn.access","tortoise.db_client"]:
        get_logger(logger)

register_tortoise(
    app,
    config={
        'connections': {
            'default': "sqlite://ims.sqlite3"
        },
        'apps': {
            'models': {
                "models": ["models","__main__"],
                'default_connection': 'default',
            }
        },
        "use_tz": False,
        "timezone": "Asia/Shanghai",
    },
    generate_schemas=True,
    add_exception_handlers=True
)

